<template>
  <view class="container">
    <form @submit="submitForm">
      <view class="form-group">
        <view class="form-item">
          <text class="label">收货人</text>
          <input 
            type="text"
            v-model="formData.name"
            placeholder="请输入收货人姓名"
            class="input"
          />
        </view>
        
        <view class="form-item">
          <text class="label">手机号码</text>
          <input 
            type="number"
            v-model="formData.phone"
            placeholder="请输入手机号码"
            maxlength="11"
            class="input"
          />
        </view>

        <view class="form-item">
          <text class="label">所在地区</text>
          <picker 
            mode="region" 
            @change="handleRegionChange"
            :value="[formData.province, formData.city, formData.district]"
          >
            <view class="picker">
              {{ formData.province || '请选择' }} {{ formData.city }} {{ formData.district }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">详细地址</text>
          <textarea
            v-model="formData.detail"
            placeholder="请输入详细地址"
            class="textarea"
          />
        </view>
      </view>

      <view class="submit-btn">
        <button type="primary" @click="submitForm">保存</button>
      </view>
    </form>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { config } from '@/utils/config.js'

// 表单数据
const formData = ref({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: ''
})

// 获取编辑数据
const initFormData = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const address = currentPage.options.address
  
  if (address) {
    try {
      const addressData = JSON.parse(decodeURIComponent(address))
      formData.value = addressData
    } catch (error) {
      console.error('Parse address data error:', error)
    }
  }
}

// 处理地区选择
const handleRegionChange = (e) => {
  const [province, city, district] = e.detail.value
  formData.value.province = province
  formData.value.city = city
  formData.value.district = district
}

// 表单提交
const submitForm = async () => {
  // 表单验证
  if (!formData.value.name.trim()) {
    return uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    })
  }
  if (!/^1\d{10}$/.test(formData.value.phone)) {
    return uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    })
  }
  if (!formData.value.province || !formData.value.city || !formData.value.district) {
    return uni.showToast({
      title: '请选择所在地区',
      icon: 'none'
    })
  }
  if (!formData.value.detail.trim()) {
    return uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    })
  }

  try {
    const url = formData.value.id 
      ? `/api/address/${formData.value.id}`
      : '/api/address'
      
    const method = formData.value.id ? 'PUT' : 'POST'
    
    const res = await uni.request({
      url: config.baseUrl + url,
      method,
      data: formData.value,
      header: {
        'Authorization': uni.getStorageSync('token'),
        'Content-Type': 'application/json'
      }
    })
    
    if (res.data.code === 200) {
      uni.showToast({
        title: formData.value.id ? '更新成功' : '添加成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      })
    } else {
      throw new Error(res.data.message)
    }
  } catch (error) {
    uni.showToast({
      title: formData.value.id ? '更新失败' : '添加失败',
      icon: 'none'
    })
  }
}

onMounted(() => {
  initFormData()
})
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 120rpx;
}

.form-group {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 0 30rpx;
  
  .form-item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 20rpx;
      display: block;
    }
    
    .input {
      height: 80rpx;
      background: #f7f8fa;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }
    
    .picker {
      height: 80rpx;
      background: #f7f8fa;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      line-height: 80rpx;
      color: #333;
      
      &:empty {
        color: #999;
      }
    }
    
    .textarea {
      width: 100%;
      height: 160rpx;
      background: #f7f8fa;
      border-radius: 12rpx;
      padding: 20rpx;
      font-size: 28rpx;
      box-sizing: border-box;
    }
  }
}

.submit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  
  button {
    height: 80rpx;
    background: #ff6b81;
    color: #fff;
    border-radius: 40rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style> 